package com.ja.openchat.views;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ja.openchat.R;
import com.lqr.emoji.EmotionLayout;
import com.lqr.emoji.IEmotionSelectedListener;
import com.lqr.emoji.LQREmotionKit;
import com.lqr.emoji.MoonUtils;
import com.lxj.xpopup.util.KeyboardUtils;
import com.zy.openchat.core.model.circle.InputBlogIdType;
import com.zy.openchat.core.model.sticker.StickerInfo;
import com.zy.openchat.util.Common;
import com.zy.openchat.util.PreventRepeatOnClickListener;

/**
 * 底部弹出评论框
 * Created by haibin
 * on 2016/11/10.
 * <p>
 * Changed by fei
 * on 2016/11/17
 *
 * @author Qiujuer
 */
@SuppressWarnings("unused")
public class BottomSheetBar {

    private View mRootView;
    private EditText mEditText;
    private ImageView mFaceView;
    private Context mContext;
    private Button mBtnCommit;
    private BottomDialog mDialog;
    private KeyboardHeightFrameLayout mFrameLayout;
    private BottomDialog mPhotoDialog;
    private EmotionLayout emotionLayout;
    InputAwareLayout inputLayout;

    private BottomSheetBar(Context context) {
        this.mContext = context;
    }

    @SuppressLint("InflateParams")
    public static BottomSheetBar delegation(Context context,InputAwareLayout inputLayout) {
        BottomSheetBar bar = new BottomSheetBar(context);
        bar.mRootView = LayoutInflater.from(context).inflate(R.layout.layout_bottom_sheet_comment_bar, null, false);
        bar.inputLayout = inputLayout;
        bar.initView();
        return bar;
    }

    private void initView() {
        emotionLayout = mRootView.findViewById(R.id.emotionLayout);
        mFrameLayout = mRootView.findViewById(R.id.fl_face);
        mEditText = mRootView.findViewById(R.id.et_comment);
        mFaceView = (ImageView) mRootView.findViewById(R.id.ivEmoj);
        mBtnCommit = (Button) mRootView.findViewById(R.id.tvSend);
        mBtnCommit.setEnabled(false);

        mDialog = new BottomDialog(mContext, false,false);
        mDialog.setContentView(mRootView);

        mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                KeyboardUtils.hideSoftInput(mEditText);
                mFrameLayout.setVisibility(View.GONE);
            }
        });

        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mBtnCommit.setEnabled(s.length() > 0);
            }
        });

        mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_SEND){
                    if(mOnBottomCallback != null){
                        mOnBottomCallback.onClickSend(mTargetId,mEditText.getText().toString());
                    }
                    KeyboardUtils.showSoftInput(mEditText);
                    return true;
                }
                return false;
            }
        });
        mFaceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inputLayout.getCurrentInput() == mFrameLayout) {
                    inputLayout.showSoftkey(mEditText);
                } else {
                    inputLayout.show(mEditText, mFrameLayout);
                }
            }
        });
        mBtnCommit.setOnClickListener(new PreventRepeatOnClickListener() {

            @Override
            public void onClickView(View v) {
                messageEmojiCount = 0;
                if(mOnBottomCallback != null){
                    mOnBottomCallback.onClickSend(mTargetId,mEditText.getText().toString());
                }
                KeyboardUtils.showSoftInput(mEditText);
            }
        });

        emotionLayout.setEmotionAddVisiable(false);
        emotionLayout.setEmotionSettingVisiable(false);
        emotionLayout.setStickerVisible(false);
        emotionLayout.setEmotionSelectedListener(new IEmotionSelectedListener() {
            @Override
            public void onEmojiSelected(String key) {
                Editable editable = mEditText.getText();
                if (key.equals("/DEL")) {
                    messageEmojiCount--;
                    messageEmojiCount = messageEmojiCount < 0 ? 0 : messageEmojiCount;
                    mEditText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
                } else {
                    if (messageEmojiCount >= MAX_EMOJI_PER_MESSAGE) {
                        Toast.makeText(mContext, "最多允许输入" + MAX_EMOJI_PER_MESSAGE + "个表情符号", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    messageEmojiCount++;
                    int code = Integer.decode(key);
                    char[] chars = Character.toChars(code);
                    String value = Character.toString(chars[0]);
                    for (int i = 1; i < chars.length; i++) {
                        value += Character.toString(chars[i]);
                    }

                    int start = mEditText.getSelectionStart();
                    int end = mEditText.getSelectionEnd();
                    start = (start < 0 ? 0 : start);
                    end = (start < 0 ? 0 : end);
                    editable.replace(start, end, value);

                    int editEnd = mEditText.getSelectionEnd();
                    MoonUtils.replaceEmoticons(LQREmotionKit.getContext(), editable, 0, editable.toString().length());
                    mEditText.setSelection(editEnd);
                }
            }

            @Override
            public void onStickerSelected(StickerInfo stickerInfo) {

            }

            @Override
            public void onStickerRemoved(StickerInfo stickerInfo) {

            }
        });
    }
    private int messageEmojiCount = 0;
    private static final int MAX_EMOJI_PER_MESSAGE = 50;
    public void destory(){
        emotionLayout.destory();
    }

    public void show(String hint, final View view) {
        mDialog.show();
        mRootView.postDelayed(new Runnable() {
            @Override
            public void run() {
                Common.showSoftKeyboard(mEditText);
            }
        }, 50);

        if(view != null){
            // 获取评论的位置,不要在CommentDialogListener.onShow()中获取，onShow在输入法弹出后才调用，
            // 此时view所属的父布局可能已经被RecyclerView回收
            final int[] coord = new int[2];
            if(view != null){
                view.getLocationOnScreen(coord);
            }
            mRootView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mOnBottomCallback != null&&view!=null) {
                        int[] inputViewCoordinatesInScreen = new int[2];
                        mRootView.getLocationOnScreen(inputViewCoordinatesInScreen);
                        inputViewCoordinatesInScreen[1] = coord[1] + view.getHeight() - inputViewCoordinatesInScreen[1];
                        // 传入 输入框距离屏幕顶部（不包括状态栏）的位置
                        mOnBottomCallback.onShow(inputViewCoordinatesInScreen);
                    }
                }
            },350);
        }

    }

    public void clean(){
        mEditText.setText("");
        dismiss();
    }

    public void dismiss() {
        KeyboardUtils.hideSoftInput(mEditText);
        mDialog.dismiss();
    }


    private InputBlogIdType mTargetId;

    public void setTargetId(InputBlogIdType targetId){
        this.mTargetId = targetId;
    }


    public EditText getEditText() {
        return mEditText;
    }

    public String getCommentText() {
        String str = mEditText.getText().toString();
        return TextUtils.isEmpty(str) ? "" : str.trim();
    }

    public Button getBtnCommit() {
        return mBtnCommit;
    }

    private OnBottomCallback mOnBottomCallback;

    public void setCallback(OnBottomCallback callback){
        this.mOnBottomCallback = callback;
    }

    public interface OnBottomCallback{
        /**
         * onShow在输入法弹出后才调用
         * @param inputViewCoordinatesOnScreen 输入框距离屏幕顶部（不包括状态栏）的位置[left,top]
         */
        void onShow(int[] inputViewCoordinatesOnScreen);

        //targetId 为空：评论主贴  不为空:评论评论
        void onClickSend(InputBlogIdType targetId,String content);
    }

}
